package net.lucamasini.ricette.server;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.orm.jpa.JpaTemplate;

public class EntityManagerFactoryListener implements ServletContextListener {

	private final static String JPATEMPLATE = "template";
	private EntityManagerFactory factory;
	private JpaTemplate template;
	
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		event.getServletContext().removeAttribute(EntityManagerFactoryListener.JPATEMPLATE);
		factory.close();
		event.getServletContext().log("factory: "+factory+ " destroyed");
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		factory = Persistence.createEntityManagerFactory("transactions-optional");
		template = new JpaTemplate(factory);
		
		event.getServletContext().setAttribute(JPATEMPLATE, template);
		
		event.getServletContext().log("JpaTemplate initialized: "+factory);
	}

	public static JpaTemplate jpaTemplateInContext(ServletContext context) {
		return (JpaTemplate) context.getAttribute(JPATEMPLATE);
	}
}
